package com.cmwa.scbp.sys.msg.adapter.impl;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.springframework.stereotype.Component;

import com.cmwa.scbp.base.mvc.entity.Employee;
import com.cmwa.scbp.sys.attach.service.AttachService;
import com.cmwa.scbp.sys.msg.constant.MessageOperationConstant;
import com.cmwa.scbp.sys.msg.service.IMessageOperationService;
import com.cmwa.scbp.sys.msg.service.IMsgBatchService;
import com.cmwa.scbp.sys.msg.service.IMsgExceptionService;
import com.cmwa.scbp.sys.msg.service.IMsgSendService;
import com.cmwa.scbp.sys.msg.service.IMsgViewService;
import com.cmwa.scbp.sys.msg.vo.ManualOperationParamsVo;
import com.cmwa.scbp.sys.msg.vo.MsgConfVo;
import com.cmwa.scbp.sys.msg.vo.MsgSourceType;
import com.cmwa.scbp.sys.msg.vo.MsgViewVo;
import com.cmwa.scbp.sys.msg.vo.MsgWaitSendVo;
import com.cmwa.scbp.utils.EmailUtil;
import com.cmwa.scbp.utils.SessionUtils;
import com.cmwa.scbp.utils.spring.SpringContextUtil;
import com.cmwa.scbp.utils.velocity.VelocityEngineTool;
import com.google.common.base.Splitter;

/**
 * velocity
 * @author ex-hejm
 * @date 2018年10月19日 下午2:49:38
 */
@Component
public class AutoOperationMessageByVelocityImpl extends AutoOperationMessageImpl {

	@Resource
	public IMessageOperationService messageOperationService;
	@Resource
	public IMsgSendService msgSendService;
	@Resource
	private IMsgBatchService msgBatchService;
	@Resource
	private IMsgExceptionService msgExceptionService;
	@Resource
	private IMsgViewService msgViewService;
	@Resource
	private AttachService attachService;

	@Override
	public List<Map<String, Object>> obtainData(ManualOperationParamsVo params) {
		List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
		Map<String, Object> data = new HashMap<String, Object>();
		datas.add(data);
		return datas;
	}

	@Override
	public List<MsgWaitSendVo> assembleMessage(MsgConfVo conf, Map<String, List<String>> confEmps, Map<String, List<Map<String, String>>> empsEmailAddress, List<Map<String, Object>> datas, ManualOperationParamsVo params) {
		List<MsgWaitSendVo> lst = new ArrayList<MsgWaitSendVo>();
		String sendType = conf.getSendType();
		if (sendType != null) {// 消息发送类型
			MsgWaitSendVo vo = new MsgWaitSendVo();
			// 收件人/抄送人empids
			vo.setEmpIds(StringUtils.join(confEmps.get("R"), ","));
			vo.setEmpIdsC(StringUtils.join(confEmps.get("C"), ","));
			VelocityEngine velocityEngine = new VelocityEngine();
			VelocityContext context = params.getDataSource();
			if (sendType.indexOf(MessageOperationConstant.MSG_TYPE_EMAIL) > -1) {// 发送类型为邮件
				//收件人（增加指定收件人）
				if(StringUtils.isNotEmpty(params.getSendToEmpIds())){
					vo.setEmpIds(StringUtils.join(confEmps.get("R"), ",") + params.getSendToEmpIds());
				}
				// 收件人/抄送人email地址
				List<String> empIdByR = EmailUtil.findEmailByEmpId(confEmps.get("R"), empsEmailAddress.get("R"));
				vo.setEmails(StringUtils.join(empIdByR, ","));
				vo.setEmailsC(StringUtils.join(EmailUtil.findEmailByEmpId(confEmps.get("C"), empsEmailAddress.get("C")), ","));

				// 公共邮件组收件人、抄送人ids、email地址
				vo.setPubEmailIds(StringUtils.join(EmailUtil.findPubEmailIdByEmailVos(conf.getPubEmailsR()), ","));
				vo.setPubEmailIdsC(StringUtils.join(EmailUtil.findPubEmailIdByEmailVos(conf.getPubEmailsC()), ","));
				vo.setPubEmails(StringUtils.join(EmailUtil.findPubEmailAddressByEmailVos(conf.getPubEmailsR()), ","));
				vo.setPubEmailsC(StringUtils.join(EmailUtil.findPubEmailAddressByEmailVos(conf.getPubEmailsC()), ","));
				
				// 模板处理
//				String template = conf.getPackVo().getContentTemplate();
				
				String titleTemplate = conf.getEmailTitleTemplate();
				String contentTemplate = conf.getEmailContentTemplate();

				vo.setType(MessageOperationConstant.MSG_TYPE_EMAIL);
				vo.setCreateId(getCurrentEmpId());
				String attIds = params.getAttIds();
				if (StringUtils.isNotBlank(attIds)) {
					vo.setAttids(attIds);// 添加附件
				}

				String other = params.getSendTo();
				if (StringUtils.isNotBlank(other)) {
					String emails = vo.getEmails() == null ? "" : vo.getEmails();
					vo.setEmails(emails + "," + other);// 添加其他收件人
				}
				StringWriter writer = new StringWriter();
				velocityEngine.evaluate(context, writer, params.getMsgCode(), contentTemplate);
				contentTemplate = writer.toString();
				
				VelocityEngine emailTemplateVE = null;
				try {
					emailTemplateVE = SpringContextUtil.getBean(VelocityEngineTool.class).getVelocityEngine();
				} catch (Exception e) {
					e.printStackTrace();
				}
				Template emailTemplateTemp = emailTemplateVE.getTemplate("/velocity/email/EMAIL_OUT_PACKAGE.vm", "UTF-8");
				// 设置初始化数据
				VelocityContext emailTemplateContext = new VelocityContext();
				emailTemplateContext.put("content", contentTemplate);
				// 设置输出
				StringWriter emailTemplateWriter = new StringWriter();
				// 将环境数据转化输出
				emailTemplateTemp.merge(emailTemplateContext, emailTemplateWriter);
				
				vo.setContent(emailTemplateWriter.toString());

				writer = new StringWriter();
				velocityEngine.evaluate(context, writer, params.getMsgCode(), titleTemplate);
				titleTemplate = writer.toString();
				vo.setTitle(titleTemplate);
				lst.add(vo);
			}
			if (sendType.indexOf(MessageOperationConstant.MSG_TYPE_NOTICE) > -1) {// 发送类型为主页通知
				String titleTemplate = conf.getNoticeTitleTemplate();// 通知的标题模板
				String contentTemplate = conf.getNoticeContentTemplate();// 通知的内容模板
				StringWriter writer = new StringWriter();
				velocityEngine.evaluate(context, writer, params.getMsgCode(), titleTemplate); // 使用Velocity引擎替换模板 标题
				titleTemplate = writer.toString();
				writer = new StringWriter();
				velocityEngine.evaluate(context, writer, params.getMsgCode(), contentTemplate);// 使用Velocity引擎替换模板 内容
				contentTemplate = writer.toString();
				String sourceId = params.getSourceId();
				if(StringUtils.isBlank(sourceId)) {
					throw new RuntimeException("ManualOperationParamsVo中参数必须要传入sourceId");
				}
				MsgSourceType sourceType = params.getSourceType();
				if(sourceType == null) {
					throw new RuntimeException("ManualOperationParamsVo中参数必须要传入sourceType");
				}
				String sendToEmpIds = params.getSendToEmpIds();
				if (StringUtils.isNotEmpty(sendToEmpIds)) {
					List<String> sendToEmpIdList = Splitter.on(",").splitToList(sendToEmpIds);
					List<String> reEmpids = confEmps.get("R");
					if (CollectionUtils.isNotEmpty(reEmpids)) {
						reEmpids.addAll(sendToEmpIdList);
					} else {
						confEmps.put("R", sendToEmpIdList);
					}
				}
				
				addIndexMessage(confEmps, titleTemplate, contentTemplate, conf.getId(), sourceId, sourceType.val());
			}
		}
		return lst;
	}
	
	/**
	 * 增加通知
	 * 
	 * @param msgWaitSendVo
	 * @param confEmps
	 * @param confId
	 * @param sourceId
	 */
	private void addIndexMessage(Map<String, List<String>> confEmps, String title, String content, String confId, String sourceId, String sourceType) {
		List<String> reEmpids = confEmps.get("R");// 消息收件人
		List<String> ccEmpids = confEmps.get("C");// 抄送人

		Set<String> empids = new HashSet<String>();// 排重
		if (reEmpids != null) {
			empids.addAll(reEmpids);
		}
		if (ccEmpids != null) {
			empids.addAll(ccEmpids);
		}

		List<MsgViewVo> msgViewVos = new ArrayList<MsgViewVo>();
		if (empids != null && !empids.isEmpty()) {
			for (String empid : empids) {
				if (StringUtils.isEmpty(empid)) {
					continue;
				}
				MsgViewVo msgViewVo = new MsgViewVo();

				msgViewVo.setMsgConfId(confId);
				msgViewVo.setEmpId(empid);
				msgViewVo.setTitle(title);
				msgViewVo.setContent(content);
				msgViewVo.setStat("INIT");
				msgViewVo.setCreateId("system");
				msgViewVo.setSourceId(sourceId);
				msgViewVo.setSourceType(sourceType);
				msgViewVo.setFlag("0");

				msgViewVos.add(msgViewVo);
			}
		}

		if (!msgViewVos.isEmpty()) {
			// 持久化 通知
			msgViewService.batchAddMsg(msgViewVos);
		}
	}

	@Override
	public IMessageOperationService getMessageOperationService() {
		return messageOperationService;
	}

	@Override
	public IMsgSendService getMsgSendService() {
		return msgSendService;
	}

	@Override
	public IMsgBatchService getMsgBatchService() {
		return msgBatchService;
	}

	@Override
	public IMsgExceptionService getMsgExceptionService() {
		return msgExceptionService;
	}

	// 当前用户ID
	private String getCurrentEmpId() {
		Employee employee = SessionUtils.getEmployee();
		return employee.getID() == null ? "system" : employee.getID();
	}

	@Override
	public AttachService getAttachService() {
		return attachService;
	}
}
